package midway.madness.post.image;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import midway.madness.R;
import midway.madness.utils.ApplicationEx;
import midway.madness.utils.SplashScreen;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.GridView;
import android.widget.TextView;

public class GalleryActivity extends Activity {

  private static GalleryStateSaver saver;
  private SplashScreen splash;
  private List<PictureObject> bitmaps = new ArrayList<PictureObject>();
  private String title, author, date, attachments;
  private Handler handler;

  public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	splash = new SplashScreen(this);
	splash.showSplash();
	setContentView(R.layout.gallery_view);

	handler = new Handler() {
	  public void handleMessage(Message msg) {
		switch (msg.what) {
		case ApplicationEx.HANDLE_ERR:
		  ApplicationEx appEx = (ApplicationEx) getApplication();
		  AlertDialog alert = appEx.handleError(GalleryActivity.this,
				  msg.getData().getString("errorMsg"));
		  alert.setOnDismissListener(new OnDismissListener() {

			public void onDismiss(DialogInterface dialog) {
			  GalleryActivity.this.finish();
			}
		  });
		  splash.removeSplash();
		  alert.show();
		  break;
		default:
		  super.handleMessage(msg);
		  break;
		}
	  }
	};

	if (null != saver) {
	  String oldAttachments = getIntent().getStringExtra("attachments");
	  if (oldAttachments.equals(saver.getAttachments())) {
		title = saver.getTitle();
		author = saver.getAuthor();
		date = saver.getDate();
		bitmaps = saver.getBitmaps();
		attachments = saver.getAttachments();
		splash.removeSplash();
	  } else {
		try {
		  populateFields(getIntent());
		} catch (IOException e) {
		  AlertDialog dialog = ((ApplicationEx) getApplication()).handleError(GalleryActivity.this,
				  "reader");
		  dialog.setOnDismissListener(new OnDismissListener() {

			public void onDismiss(DialogInterface dialog) {
			  splash.removeSplash();
			  GalleryActivity.this.finish();
			}
		  });
		  dialog.show();
		  return;
		}
	  }
	} else {
	  try {
		populateFields(getIntent());
	  } catch (IOException e) {
		AlertDialog dialog = ((ApplicationEx) getApplication()).handleError(GalleryActivity.this,
				"reader");
		dialog.setOnDismissListener(new OnDismissListener() {

		  public void onDismiss(DialogInterface dialog) {
			splash.removeSplash();
			GalleryActivity.this.finish();
		  }
		});
		dialog.show();
		return;
	  }
	}
  }

  public void onStop() {
	super.onStop();
	if (null == saver) {
	  saver = new GalleryStateSaver();
	}
	saver.setAuthor(author);
	saver.setBitmaps(bitmaps);
	saver.setDate(date);
	saver.setTitle(title);
	saver.setShowSplash(true);
	saver.setAttachments(attachments);
  }

  private void populateFields(Intent pastIntent) throws IOException {
	title = pastIntent.getStringExtra("title");
	author = pastIntent.getStringExtra("author");
	date = pastIntent.getStringExtra("date");
	attachments = pastIntent.getStringExtra("attachments");

	new DownloadPicturesTask().execute(attachments);
  }

  private class DownloadPicturesTask extends AsyncTask<String, Void, List<PictureObject>> {

	@Override
	protected List<PictureObject> doInBackground(String... params) {
	  List<PictureObject> retVal = new ArrayList<PictureObject>();
	  JSONArray images;
	  try {
		images = new JSONArray(params[0]);
		for (int i = 0; i < images.length(); i++) {
		  JSONObject image = (JSONObject) images.get(i);
		  JSONObject temp = image.getJSONObject("images");
		  String thumbnail = temp.getJSONObject("thumbnail").getString("url");
		  String regular = temp.getJSONObject("large").getString("url");
		  try {
			retVal.add(new PictureObject(GalleryActivity.this, author, title, date, thumbnail,
					((ApplicationEx) getApplication()).loadBitmap(thumbnail), regular));
		  } catch (IOException e) {
			e.printStackTrace();
		  }
		}
	  } catch (JSONException e1) {
		Bundle data = new Bundle();
		data.putString("errorMsg", ((ApplicationEx) getApplication()).getMessage("reader"));
		Message msg = new Message();
		msg.setData(data);
		msg.what = ApplicationEx.HANDLE_ERR;
		handler.sendMessage(msg);
	  }
	  return retVal;
	}

	protected void onPostExecute(List<PictureObject> result) {
	  bitmaps = result;
	  splash.removeSplash();
	  splash = null;
	  if (null != bitmaps && !bitmaps.isEmpty()) {
		((TextView) findViewById(R.id.gallery_title)).setText(title);
		((TextView) findViewById(R.id.gallery_author))
				.setText(date + " BY " + author.toUpperCase());
		GridView gallery = (GridView) findViewById(R.id.gallery_grid);
		gallery.setAdapter(new MidwayGalleryAdapter(GalleryActivity.this, bitmaps));
	  } else {
		Bundle data = new Bundle();
		data.putString("errorMsg", ((ApplicationEx) getApplication()).getMessage("unknown"));
		Message msg = new Message();
		msg.what = ApplicationEx.HANDLE_ERR;
		msg.setData(data);
		handler.sendMessage(msg);
	  }
	}

  }

}
